package de.hs.rm;

import java.util.ArrayList;
import java.util.Set;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.graphics.Bitmap;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

public class BHMainActivity extends Activity
{
	private static final int REQUEST_ENABLE_BT = 1;
	
	private LinearLayout startscreen;
	private Dialog dialogDeviceList;
	private ProgressDialog dialogDeviceSearch;
	
	private BHMainApplication mainApp= null;
	
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        prepareImages();
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);
        
        
        mainApp = (BHMainApplication)this.getApplicationContext();
        mainApp.setCurrentHandler(mHandler);
        
        startscreen = (LinearLayout) findViewById(R.id.start_screen);
        startscreen.setOnClickListener(
        	new OnClickListener() {
	    		@Override
	    		public void onClick(View v) {
	    			if(!mainApp.isConnected())
	    				mainApp.startConnectionThread();
	    			else
	    				openModeActivity();
	    				
	    		}				
        	}
        );
    }
    private void prepareImages()
    {
    	ImageConverter.decodeSampledBitmapFromResource(getResources(), R.drawable.bluetoothgreen, 200, 200);
    }
    
    @Override
    public void onBackPressed() {
    	if(mainApp.isConnected()) 
    	{
    		mainApp.closeApp();
    	}
    	super.onBackPressed();
    	return;
    }
    
    private final Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what)
            {
	            case BTMessage.BT_NOT_AVAILABLE:
	            	closeActivity();
	            	break;
	            case BTMessage.BT_NOT_ENABLED:
	            	startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), 0);
	                break;
	            case BTMessage.BT_DISCOVERY_STARTED:
	            	openSearchDialog();
	                break;
	            case BTMessage.BT_DISCOVERY_FINISHED:
	            	dialogDeviceSearch.dismiss();
	            	openDeviceDialog((ArrayList<BluetoothDevice>)msg.obj);
	                break;
	            case HANDLER_MSG.CONNECTION_ESTABLISHED:
	            	Toast.makeText(getApplicationContext(), "Connection established!", Toast.LENGTH_SHORT).show();
	            	openModeActivity();
	                break;
	            case HANDLER_MSG.CONNECTION_FAILED:
	            	Toast.makeText(getApplicationContext(), "Connection failed: " + (String)msg.obj, Toast.LENGTH_SHORT).show();
	                break;
	                
	            case HANDLER_MSG.CONNECTION_LOST:
	            	Toast.makeText(getApplicationContext(), "Connection lost!", Toast.LENGTH_SHORT).show();
	                break;
            }
            
        }
    };
	
	 @Override
	 protected void onActivityResult(int requestCode, int resultCode, Intent data)
	 {
		 if(requestCode == REQUEST_ENABLE_BT)
			 mainApp.startConnectionThread();
	 }
	
	protected void closeActivity()
	{
		finish();
	}
	
	protected void openSearchDialog()
	{
		dialogDeviceSearch =  new ProgressDialog(this);
		dialogDeviceSearch.setMessage(getString(R.string.scanning));
		dialogDeviceSearch.setCancelable(false);	
		dialogDeviceSearch.show();
	}
	
	protected void openDeviceDialog(ArrayList<BluetoothDevice> btDevices) {
		
		ArrayAdapter<String> btDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.listview_item);
		if (btDevices.size() > 0) {
            for (BluetoothDevice device : btDevices) {
            	//if(mainApp.testCommunication(device.getAddress()))          	
            	btDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
            }
		}
		dialogDeviceList = new Dialog(this);
		dialogDeviceList.setTitle(getString(R.string.select_device));
		
		ListView lvDeviceList = new ListView(this);
		lvDeviceList.setAdapter(btDevicesArrayAdapter);
        lvDeviceList.setOnItemClickListener(btDeviceClickListener);
		
        dialogDeviceList.setContentView(lvDeviceList);
        dialogDeviceList.show();
	}
	
	// The on-click listener for all devices in the ListViews
    private OnItemClickListener btDeviceClickListener = new OnItemClickListener() {
        public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
            // Cancel discovery because it's costly and we're about to connect
        	// Get the device MAC address, which is the last 17 chars in the View
            String info = ((TextView) v).getText().toString();
            //mainApp.setAddress();
            dialogDeviceList.dismiss();
            mainApp.startCommunicationThread(info.substring(info.length() - 17));
                        
        }
    };
    
    private void openModeActivity()
    {
    	Intent intent = new Intent(BHMainActivity.this, BHModeActivity.class);
		startActivity(intent); 			
    }  
    
}
